package com.david.mydemo.ctl_ocr.service;

import com.alibaba.fastjson.JSON;
import com.david.mydemo.ctl_ocr.utils.GatewayUtils;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lyz
 * @Title: HttpPostGatewayService
 * @Description:
 * @date 2020/9/7 15:44
 */
public class HttpPostGatewayService<T> {
    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json;charset=utf-8");

    public Response recongize(String baseUrl, String path, String appid, String appkey, String callback, T bodyParam) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(20, TimeUnit.SECONDS).build();
        String xCurTime = new Date().getTime() / 1000 + "";
        StringBuilder sb = new StringBuilder(GatewayUtils.getCapabilityName(path));
        while (sb.length() < 24){
            sb.append(0);
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String csid = appid + sb + uuid;
        String xServerParam = GatewayUtils.getBase64("{\"appid\":\"" + appid + "\",\"csid\":\"" + csid + "\"}");
        String xCheckSum= DigestUtils.md5Hex(appkey + xCurTime + xServerParam);
        RequestBody body = RequestBody.create(JSON_MEDIA_TYPE,JSON.toJSONString(bodyParam));
        Request request = new Request.Builder().url(baseUrl + path)
                .addHeader("X-Server-Param",xServerParam)
                .addHeader("X-CheckSum",xCheckSum)
                .addHeader("X-CurTime",xCurTime)
                .addHeader("X-Callback-URL",callback)
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .post(body).build();
        return client.newCall(request).execute();
    }
}
